import { useEffect, useMemo, useState } from 'react';
import { Button, Spin, Tabs, message } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { ContractWarnTabsPane } from './ContractWarnTabsPane';
import Cls from 'classnames';
import InfiniteScroll from 'react-infinite-scroller';
import '../common/styles.less';
import pageStyles from '@/common/pageLayout.less';
import { getContractWarnDataSercvice } from '../services';

export const ContractWarnView: React.FC<ContractWarnAPI.IContractWarnView> = ({ curRes }) => {
  const styleFixCls = 'contract-warn'; /** 样式根目录 */
  const [tabPaneKey, setTabPaneKey] = useState<string>('1'); /** 存入选中的tab标识 */
  const [manageDataList, setManageDataList] = useState<Record<string, any>[]>([]); /** 保存合同预警数据 */
  const [isOnReload, setIsOnReload] = useState<boolean>(false);

  /**
   * 保存的分页参数
   */
  const [scrollObj, setScrollObj] = useState<any>({
    total: 0,
    count: 0,
    loading: false,
    hasMore: true,
    limit: 5,
  });

  const getContractWarnDataCallback = (res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    } else {
      setManageDataList(res?.rows);
      setScrollObj({
        ...scrollObj,
        loading: false,
        total: res.total,
      });
    }
    setIsOnReload(false);
  };
  /**
   * 引入获取预警接口
   */
  const { getContractWarnDataRun, getContractWarnDataLoading } = getContractWarnDataSercvice(curRes, getContractWarnDataCallback);

  /**
   * 初始化获取数据
   */
  const defaultGetWarnData = () => {
    let { count, limit } = scrollObj;
    count++;
    setScrollObj({
      ...scrollObj,

      count: count,
      loading: true,
    });
    let payload = {
      page: 1,
      rows: count * 10 + limit,
    };
    getContractWarnDataRun(payload);
  };

  useEffect(() => {
    defaultGetWarnData();
  }, []);

  /**
   * 处理滚动加载
   */
  const handleInfiniteOnLoad = () => {
    const { total } = scrollObj;
    if (manageDataList?.length >= total) {
      message.warning('没有更多数据了哦');
      setScrollObj({
        ...scrollObj,
        hasMore: false,
        loading: false,
      });
      return;
    }
    defaultGetWarnData();
  };

  /** 返回子组件 */
  const renderTabsPane = () => {
    return (
      <ContractWarnTabsPane
        styleClassName={styleFixCls}
        contractInfoList={manageDataList}
        // reloadManage={reloadRefresh}
        reloadManage={() => {
          defaultGetWarnData();
        }}
        curRes={curRes}
      />
    );
  };

  /** 刷新回调 */
  const reloadHomeCallback = () => {
    // reloadRefresh();
    setScrollObj({
      ...scrollObj,
      count: 0,
    });
    setIsOnReload(true);
  };

  useEffect(() => {
    if (scrollObj?.count == 0 && isOnReload) {
      defaultGetWarnData();
    }
  }, [scrollObj?.count, isOnReload]);

  /** 刷新 */
  const tabsExtraBtns = () => {
    return <Button type="primary" icon={<ReloadOutlined />} onClick={reloadHomeCallback} />;
  };

  /** tabs子页面 */
  const tabsItem = useMemo(() => {
    let items: any[] = [
      {
        label: '提醒事项',
        key: '1',
        forceRender: true,
        children: (
          <div className={pageStyles['InfiniteScrollView']}>
            <InfiniteScroll
              loadMore={handleInfiniteOnLoad}
              initialLoad={false}
              pageStart={1}
              useWindow={false}
              hasMore={!scrollObj?.loading && scrollObj?.hasMore}
              className="InfiniteScrollDiv"
            >
              {renderTabsPane()}
            </InfiniteScroll>
          </div>
        ),
        isShow: curRes['/warnController/contractHomePage'] || false,
      },
    ];

    const newItems: any[] = items?.filter((item: any) => item?.isShow);
    return newItems;
  }, [manageDataList, curRes]);

  return (
    <div className={Cls(`${styleFixCls}`, pageStyles['commonTabsLine'])}>
      <Spin spinning={getContractWarnDataLoading}>
        <Tabs
          activeKey={tabPaneKey}
          tabBarExtraContent={tabsExtraBtns()}
          items={tabsItem}
          onChange={(activeKey: string) => {
            setTabPaneKey(activeKey);
          }}
        />
      </Spin>
    </div>
  );
};
